package dao

import (
	"context"
	"gin_mall_tmp/model"
	"gorm.io/gorm"
)

type FavouriteDao struct {
	*gorm.DB
}

func NewFavouriteDao(ctx context.Context) *FavouriteDao {
	return &FavouriteDao{NewDBClient(ctx)}
}

func NewFavouriteDaoByDB(db *gorm.DB) *FavouriteDao {
	return &FavouriteDao{db}
}

func (dao *FavouriteDao) ListFavourite(uId uint) (resp []*model.Favourite, err error) {
	err = dao.DB.Model(&model.Favourite{}).Where("user_id=?", uId).Find(&resp).Error
	return
}

func (dao *FavouriteDao) FavouriteExistOrNot(pId, uId uint) (exist bool, err error) {
	var count int64
	err = dao.DB.Model(&model.Favourite{}).Where("product_id=? AND user_id=?", pId, pId).Count(&count).Error
	if err != nil {
		return false, err
	}
	if count == 0 {
		return false, err
	}
	return true, nil
}

func (dao *FavouriteDao) CreateFavourite(in *model.Favourite) error {
	return dao.DB.Model(&model.Favourite{}).Create(&in).Error
}

func (dao *FavouriteDao) DeleteFavourite(uId, fId uint) error {
	return dao.DB.Model(&model.Favourite{}).
		Where("id=? AND user_id=?", fId, uId).Delete(&model.Favourite{}).Error
}
